package cn.italkcloud.cph.service.impl;

import cn.italkcloud.cph.entity.VosGroupRelate;
import cn.italkcloud.cph.mapper.VosGroupRelateMapper;
import cn.italkcloud.cph.service.IVosGroupRelateService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * VOS账号组关联 服务实现类
 * </p>
 *
 * @author dominate
 * @since 2025-03-07
 */
@Service
public class VosGroupRelateServiceImpl extends ServiceImpl<VosGroupRelateMapper, VosGroupRelate> implements IVosGroupRelateService {

    @Override
    public boolean addRelate(int accountId, int groupId, int customerId) {
        VosGroupRelate insert = new VosGroupRelate()
                .setAccountId(accountId)
                .setGroupId(groupId)
                .setCustomerId(customerId);
        return save(insert);
    }

    @Override
    public List<Integer> getCustomerIdList(int groupId) {
        QueryWrapper<VosGroupRelate> query = new QueryWrapper<>();
        query.lambda().eq(VosGroupRelate::getGroupId, groupId)
                .select(VosGroupRelate::getCustomerId);
        List<VosGroupRelate> list = list(query);
        List<Integer> customerIdList = new ArrayList<>(list.size());
        for (VosGroupRelate relate : list) {
            customerIdList.add(relate.getCustomerId());
        }
        return customerIdList;
    }

    @Override
    public Map<Integer, List<Integer>> getGroupCustomerMap(int accountId) {
        QueryWrapper<VosGroupRelate> query = new QueryWrapper<>();
        query.lambda().eq(VosGroupRelate::getAccountId, accountId)
                .select(VosGroupRelate::getCustomerId, VosGroupRelate::getGroupId);
        List<VosGroupRelate> list = list(query);
        Map<Integer, List<Integer>> groupCustomerMap = new HashMap<>();
        for (VosGroupRelate relate : list) {
            if (!groupCustomerMap.containsKey(relate.getGroupId())) {
                groupCustomerMap.put(relate.getGroupId(), new ArrayList<>());
            }
            groupCustomerMap.get(relate.getGroupId()).add(relate.getCustomerId());
        }
        return groupCustomerMap;
    }

    @Override
    public boolean remove(int accountId, int groupId, int customerId) {
        QueryWrapper<VosGroupRelate> query = new QueryWrapper<>();
        query.lambda().eq(VosGroupRelate::getAccountId, accountId)
                .eq(VosGroupRelate::getGroupId, groupId)
                .eq(VosGroupRelate::getCustomerId, customerId);
        return remove(query);
    }

}
